from pprint import pprint
import time
from pycaw.pycaw import AudioUtilities
import psutil

def get_media_sessions_simple():
    """简化版本 - 只获取基本的媒体会话信息"""
    sessions = AudioUtilities.GetAllSessions()
    
    media_sessions = []
    
    for session in sessions:
        if session.Process and session.Process.name():
            process_name = session.Process.name()
            
            # 检查是否是常见的媒体播放器
            media_players = ['spotify', 'vlc', 'music', 'wmplayer', 'groove', 
                           'msedge', 'chrome', 'firefox', 'itunes', 'winamp',
                           'audacity', 'dopamine', 'aimp', 'musicbee']
            
            if any(player in process_name.lower() for player in media_players):
                session_info = {
                    'process_name': process_name,
                    'process_id': session.ProcessId,
                    'state': str(session.State)
                }
                
                # 尝试获取进程命令行（可能包含播放信息）
                try:
                    process = psutil.Process(session.ProcessId)
                    cmd_line = " ".join(process.cmdline())
                    session_info['cmd_line'] = cmd_line
                    
                    # 从命令行中尝试提取标题信息
                    title = extract_title_from_cmdline(cmd_line, process_name)
                    if title:
                        session_info['title'] = title
                        
                except (psutil.NoSuchProcess, psutil.AccessDenied):
                    session_info['cmd_line'] = "N/A"
                
                media_sessions.append(session_info)
    
    return media_sessions

def extract_title_from_cmdline(cmdline, process_name):
    """从命令行参数中尝试提取标题"""
    cmdline_lower = cmdline.lower()
    process_name_lower = process_name.lower()
    
    # 针对不同播放器的特定提取逻辑
    if 'spotify' in process_name_lower:
        # Spotify 通常会在窗口标题中显示歌曲信息
        return "Spotify (需要在窗口标题中获取)"
    
    elif 'vlc' in process_name_lower:
        # VLC 通常在命令行中直接包含文件路径
        import re
        # 查找可能是媒体文件的路径
        media_extensions = ['.mp3', '.mp4', '.avi', '.mkv', '.flac', '.wav']
        for ext in media_extensions:
            if ext in cmdline_lower:
                # 提取文件名（不含路径和扩展名）
                pattern = r'[^\\/]+' + re.escape(ext)
                match = re.search(pattern, cmdline)
                if match:
                    filename = match.group().replace(ext, '')
                    return filename
        return "VLC 媒体文件"
    
    elif 'music' in process_name_lower or 'groove' in process_name_lower:
        return "Windows Media Player"
    
    return None

def print_simple_media_info():
    """打印简化的媒体信息"""
    sessions = get_media_sessions_simple()
    
    print("=" * 40)
    print("当前媒体播放器:")
    print("=" * 40)
    
    if not sessions:
        print("未检测到媒体播放器")
        return
    
    for i, session in enumerate(sessions, 1):
        print(f"{i}. {session['process_name']}")
        print(f"   进程ID: {session['process_id']}")
        print(f"   状态: {session['state']}")
        
        if 'title' in session:
            print(f"   标题: {session['title']}")
        else:
            print(f"   标题: 需要其他方法获取")
        
        print("-" * 20)

# 更简单的版本 - 只列出媒体播放器
def list_media_players():
    """只列出检测到的媒体播放器"""
    sessions = AudioUtilities.GetAllSessions()
    
    media_players = []
    
    for session in sessions:
        if session.Process and session.Process.name():
            process_name = session.Process.name().lower()
            
            # 常见媒体播放器
            media_keywords = [
                'spotify', 'vlc', 'music', 'groove', 'itunes',
                'winamp', 'foobar', 'aimp', 'musicbee', 'windowsmediaplayer',
                'audacity', 'dopamine', 'potplayer', 'mpc', 'kmplayer'
            ]
            
            if any(keyword in process_name for keyword in media_keywords):
                # 获取原始进程名（不转小写）
                original_name = session.Process.name()
                if original_name not in [p['name'] for p in media_players]:
                    media_players.append({
                        'name': original_name,
                        'pid': session.ProcessId
                    })
    
    return media_players

if __name__ == "__main__":
    # 运行简单版本
    while 1:
        pprint(get_media_sessions_simple())
        time.sleep(0.2)

# [{'cmd_line': 'C:\\Program Files '
#               '(x86)\\Microsoft\\Edge\\Application\\msedge.exe --type=utility '
#               '--utility-sub-type=audio.mojom.AudioService --lang=zh-CN '
#               '--service-sandbox-type=audio '
#               '--video-capture-use-gpu-memory-buffer --no-pre-read-main-dll '
#               '--skip-read-main-dll '
#               '--metrics-shmem-handle=9592,i,9974291630467662913,10693495227684115007,524288 '
#               '--field-trial-handle=1952,i,124140110466759564,10986184126416396633,262144 '
#               '--enable-features=ParallelDownloading --variations-seed-version '
#               '--mojo-platform-channel-handle=3180 /prefetch:12',
#   'process_id': 28840,
#   'process_name': 'msedge.exe',
#   'state': '0'}]